﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Speech.Recognition;
using System.IO;

namespace TTS
{
    public class Recognition
    {
        public static string NON_DETECT = "NON_DETECT";

        private SpeechRecognitionEngine sre;
        private string result;
        
        public Recognition(){
            // Create a new SpeechRecognitionEngine instance.
            sre = new SpeechRecognitionEngine();
        }

        private void sre_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
        {
            result = e.Result.Text;            
        }

        public string detect(byte[] byteArray)
        {
            Stream input = new MemoryStream(byteArray);

            // Configure the input to the recognizer.
            this.sre.SetInputToWaveStream(input);

            // Create a simple grammar that recognizes "red", "green", or "blue".
            Choices colors = new Choices();
            colors.Add(new string[] { "red", "green", "blue", "turn on", "back", "repeat" });

            // Create a GrammarBuilder object and append the Choices object.
            GrammarBuilder gb = new GrammarBuilder();
            gb.Append(colors);

            // Create the Grammar instance and load it into the speech recognition engine.
            Grammar g = new Grammar(gb);
            this.sre.LoadGrammar(g);

            // Register a handler for the SpeechRecognized event.
            this.sre.SpeechRecognized += new EventHandler<SpeechRecognizedEventArgs>(sre_SpeechRecognized);

            // Start recognition.
            this.sre.Recognize();
            return result;
        }
    }
}